<template>
  <div class='settlement'>
    <van-nav-bar title="提交订单" left-text="" left-arrow @click-left="$router.go(-1)" />
    <div class="bg"></div>

    <div class="product_info">
      <van-cell-group inset>
        <van-cell class="shopname" label="已点商品">
          <template #title>
            <img src="../assets/img/local.png">
            <span>{{ shop.address }}</span>
          </template>
        </van-cell>
        <van-cell class="card">
          <van-card v-for="(item, index) in products " :key="index" :num="item.quantity" :desc="item.describe" :title="item.product_name" :thumb="domain + item.imageurl">
            <template #price>
              <div class="price">￥<span>{{ item.sale_price }}</span></div>
            </template>
          </van-card>
        </van-cell>
        <van-cell title="配送费" :value="price.express_fee > 0 ? express_fee : '免配送费'" />
        <van-cell :title="`共${price.totality}件`" :value="`小计：￥${price.products_amount}`" />
      </van-cell-group>
    </div>

    <van-cell-group inset>
      <van-cell title="支付方式" />
      <van-cell class="pey_type" title="微信支付">
        <template #icon>
          <van-icon name="wechat-pay" color="#43C93E" />
        </template>
        <template #default>
          <van-radio-group v-model="radio">
            <van-radio name="1" checked-color="#DB5310"></van-radio>
          </van-radio-group>
        </template>
      </van-cell>
    </van-cell-group>

    <van-cell-group class="send_info" inset>
      <van-cell title="配送信息" />
      <van-field v-model="receive_name" label="下单姓名" placeholder="请填写下单姓名" input-align="right" />
      <van-field v-model="r_phone" type="tel" label="联系电话" placeholder="请填写联系电话" input-align="right" />
      <van-field v-model="r_address" label="配送地址" placeholder="请填写配送地址" input-align="right" />
    </van-cell-group>

    <van-cell-group class="send_info" inset>
      <van-field v-model="receive_time_show" label="配送时间" placeholder="请选择配送时间" input-align="right" is-link readonly @click="showPicker = true" />
    </van-cell-group>

    <div class="cart">
      <div class="number">
        <div class="sum1">
          <span><span>共计￥</span>{{ price.pay_amount }}</span>
          <span>免配送费</span>
        </div>
      </div>
      <div class="submit" @click="onPay">去支付</div>
    </div>

    <van-popup v-model="showPicker" position="bottom" round :style="{ height: '55%' }">
      <van-datetime-picker v-model="currentDate" type="datetime" :formatter="formatter" :filter="filterDate" :min-date="minDate" :max-date="maxDate" @confirm="onConfirm" @cancel="showPicker = false" />
    </van-popup>
  </div>
</template>

<script>
import { Toast } from 'vant';
export default {
  data () {
    return {
      shop: {},
      products: [],
      price: {},
      radio: '1',
      receive_name: '',
      r_phone: '',
      r_address: '',
      receive_time: '',
      receive_time_show: '',
      minDate: null,
      maxDate: null,
      currentDate: new Date(),
      showPicker: false,
    }
  },
  created () {
    this.setDynamicTimeRange()
    this.getSettlement()
  },
  computed: {
    formattedMinHourMin () {
      const [hour, minute] = this.shop.lunch[0].split(':').map(Number);
      return new Date(0, 0, 0, hour, minute);
    },
    formattedMaxHourMin () {
      const [hour, minute] = this.shop.dinner[1].split(':').map(Number);
      return new Date(0, 0, 0, hour, minute);
    },
  },
  methods: {
    getSettlement () {
      this.$axios.post(this.$api.Settlement, {
        cart_ids: this.$route.query.ids
      }).then(res => {
        if (res.data.code == 1) {
          this.products = res.data.data.products
          this.price = res.data.data.price
        } else {
          Toast.fail(res.data.msg)
        }
      })
    },
    formatter (type, value) {
      if (type === 'year') return '';
      if (type === 'month') return `${value}月`;
      if (type === 'day') return `${value}日`;
      if (type === 'hour') return `${value}点`;
      if (type === 'minute') return `${value}分`;
      return value;
    },
    filterDate (type, options) {
      if (type === 'hour') {
        const currentHour = new Date().getHours();
        const currentMinute = new Date().getMinutes();
        let curr = 60 - currentMinute
        if (curr < 30) options = options.filter(item => item != currentHour)
        return options.filter((option) => option <= this.maxHour && option >= this.minHour);
      }
      if (type === 'minute') {
        return options.filter((option) => option % 30 === 0);
      }
      return options;
    },
    setDynamicTimeRange () {
      this.shop = this.$store.state.shop
      const now = new Date();
      const maxDaysLater = new Date(now);
      maxDaysLater.setDate(now.getDate() + this.shop.ahead_days);
      this.minDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, this.formattedMinHourMin.getHours(), now.getMinutes());
      this.maxDate = new Date(maxDaysLater.getFullYear(), maxDaysLater.getMonth(), maxDaysLater.getDate(), this.formattedMaxHourMin.getHours(), this.formattedMaxHourMin.getMinutes())
      this.minHour = this.shop.lunch[0].split(':').map(Number)[0]
      this.maxHour = this.shop.dinner[1].split(':').map(Number)[0]
    },
    onConfirm (val) {
      let selectedDate = new Date(val);
      let hour = selectedDate.getHours();
      let minute = selectedDate.getMinutes();
      let adjustedMinute = minute >= 30 ? 30 : 0;
      let adjustedDate = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), selectedDate.getDate(), hour, adjustedMinute, 0, 0);
      let show = this.$dayjs(adjustedDate).format('YYYY年MM月DD日 HH:mm');
      this.receive_time_show = show;
      this.receive_time = Math.floor(adjustedDate.getTime() / 1000);
      this.showPicker = false;
    },
    onPay () {
      if (this.receive_name !== '' && this.r_phone !== '' && this.r_address !== '' && this.receive_time_show !== '') {
        this.$axios.post(this.$api.GoToPlace, {
          cart_ids: this.$route.query.ids,
          receive_name: this.receive_name,
          r_phone: this.r_phone,
          r_address: this.r_address,
          receive_time: this.receive_time,
        }).then(res => {
          if (res.data.code == 1) {
            this.StartWeiXinPay(res.data.data)
          } else {
            Toast.fail(res.data.msg)
          }
        })
      } else {
        Toast.fail('缺少收货信息')
      }
    },
    // 调取微信支付
    StartWeiXinPay (pay_params) {
      if (typeof window.WeixinJSBridge === 'undefined') {
        if (document.addEventListener) {
          document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady(pay_params), false)
          alert(1);
        } else if (document.attachEvent) {
          alert(2);
          document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady(pay_params))
          document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady(pay_params))
        }
      } else {
        this.onBridgeReady(pay_params)
      }
    },
    onBridgeReady (pay_params) {
      var that = this
      window.WeixinJSBridge.invoke('getBrandWCPayRequest', {
        'appId': pay_params.appId, // 公众号名称，由商户传入
        'timeStamp': pay_params.timeStamp, // 时间戳，自1970年以来的秒数
        'nonceStr': pay_params.nonceStr, // 随机串
        'package': pay_params.package, //统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
        'signType': pay_params.signType, // 微信签名方式：
        'paySign': pay_params.paySign // 微信签名
      },
        function (res) {
          if (res.err_msg == 'get_brand_wcpay_request:ok') {
            // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
            that.$router.replace('payFinish')
          } else {
            Toast.fail('支付失败')
          }
        }
      )
    },
  },
}
</script>

<style scoped lang='less'>
.settlement {
  padding-bottom: 100px;

  .van-cell-group {
    margin: 0 10px 12px;
    border-radius: 6px;
  }

  /deep/.van-hairline--bottom::after {
    border: 0;
  }

  .bg {
    position: absolute;
    top: 46px;
    left: 0;
    width: 100%;
    height: 55px;
    background-color: #DB5310;
  }

  .product_info {
    padding-top: 10px;


    .shopname {

      .van-cell__title,
      .van-cell__label {
        color: #5F5F5F;
        font-size: 16px;
      }

      img {
        margin-right: 10px;
        transform: translateY(2px);
        filter: grayscale(100%);
      }
    }

    .card {
      .van-card {
        padding: 0;
        background-color: #fff;

        .van-card__thumb {
          width: 68px;
          height: 68px;
        }

        .van-card__title {
          color: #494B4E;
          font-size: 16px;
          margin-bottom: 4px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
        }

        .price {
          color: #5F5F5F;
          font-size: 16px;
          font-weight: bold;
        }
      }
    }

    .time {
      color: #999999;
      font-size: 12px;
    }

    .total {
      color: #494B4E;
      font-size: 14px;
      font-weight: bold;
    }
  }

  .pey_type {

    .van-icon {
      font-size: 26px;
      margin-right: 8px;
    }

    .van-cell__value {
      .van-radio {
        justify-content: flex-end;
      }
    }
  }

  .cart {
    position: fixed;
    bottom: 15px;
    width: calc(100% - 30px);
    height: 55px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 0 15px;
    padding: 5px;
    border-radius: 50px;
    background-color: #494B4E;
    box-sizing: border-box;
    z-index: 9999;


    .number {
      display: flex;
      align-items: center;

      .sum1 {
        color: #F3F3F3;
        font-size: 16px;
        padding-left: 16px;
      }

      .sum1 {
        display: flex;
        flex-direction: column;

        span:nth-child(1) {
          font-size: 16px;
          font-weight: bold;

          span {
            font-weight: normal;
          }
        }

        span:nth-child(2) {
          font-size: 10px;
        }
      }
    }

    .submit {
      width: 108px;
      height: 46px;
      line-height: 46px;
      color: #fff;
      font-size: 20px;
      text-align: center;
      border-radius: 50px;
      background-color: #DB5310;
    }
  }
}
</style>
